package network.client;

import java.io.IOException;

import driver.PersonDriver;

import messages.BaseMessage;
import messages.observer.CurrentStateMessage;
import messages.observer.CurrentStateRequest;
import messages.observer.EventCollectionMessage;
import observer.ObserverListener;
import state.group.events.BaseEvent;
import state.group.events.EventCollection;
import state.group.events.EventType;
import system.GlobalData;

public class PersonDispatcherListener implements ObserverListener {

    @Override
    public void handleMessage(BaseMessage message)
    {
        
        switch (message.getMessageType())
        {
            case EventCollectionMessage:
                EventCollectionMessage collMess = (EventCollectionMessage) message;
                EventCollection events = collMess.getEvents();
                
                GlobalData.partialState.updateStructsUsingEvents(events);
                
                boolean hasRefreshEvent = false;
                
                for (BaseEvent e : events)
                {
                    PersonDriver.getInstance().handleEvent(e);
                    
                    if (e.getEventType() == EventType.RegistrationEvent)
                    {
                        hasRefreshEvent = true;
                    }
                }
                
                if (hasRefreshEvent)
                {
                    CurrentStateRequest request = new CurrentStateRequest();
                    
                    try
                    {
                        GlobalData.elevatorThread.getRemoteSocket().getOutputStream().write(request.toByteArray());
                    }
                    catch (IOException e1)
                    {
                        e1.printStackTrace();
                    }
                }
                
                break;
            case DeregistrationMessage:
                
                break;
            case CurrentStateMessage:
                CurrentStateMessage curStateMess = (CurrentStateMessage) message;
                try
                {
                    GlobalData.setGroupDispatcherState(curStateMess);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                break;
        }
        
    }

}
